package com.zaizai.gulimall.product.exception;


import com.zaizai.common.exception.BizCodeEnum;
import com.zaizai.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestControllerAdvice(basePackages ="com.zaizai.gulimall.product.controller" )
public class GulimallExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
            Map<String,String> errorMap = new HashMap<>();
            //获取校验的错误信息
            bindingResult.getFieldErrors().forEach((item)->{
                //获取错误提示
                String message = item.getDefaultMessage();
                //获取错误属性名字
                String field = item.getField();
                errorMap.put(field,message);

            });
            return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data",errorMap);

    }
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable){
        log.error("错误",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }

}
